//
//  APPLEComposeViewController.swift
//  123
//
//  Created by pangjiaxing on 16/1/7.
//  Copyright © 2016年 pangjiaxing. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
import AFNetworking

let APPLEComposeViewControllerMargin:CGFloat = 8
class APPLEComposeViewController: UIViewController {
    
    var toolBarAnimation:Bool = true
    
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        // 设置不同状态的文字颜色
        button.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        // 设置文字以及字体大小
        button.setTitle("发送", forState: UIControlState.Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        
        button.frame.size = CGSize(width: 40, height: 30)
        button.addTarget(self, action: "sendMessage", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    private lazy var titleView:UILabel={
        let titleView:UILabel = UILabel()
        titleView.numberOfLines=0
        titleView.textAlignment = .Center
        return titleView
    }()
    
    private lazy var textView:APPLETextView = {
        let textView = APPLETextView()
        textView.delegate = self
        textView.font = UIFont.systemFontOfSize(16)
//        textView.keyboardDismissMode = .OnDrag
        textView.alwaysBounceVertical = true
       return textView
    }()
    
    private lazy var toolBar:APPLEComposeToolBar = {
        let toolBar = APPLEComposeToolBar(frame: CGRectZero)
            toolBar.buttonClickCloures = {[weak self] (type) -> ()in
                
                switch type {
                case .Picture:
                     print("相册")
                     self!.selectPictureButton()
                case .Mention:
                    print("@")
                case .Trend:
                    print("#")
                case .Emoticon:
                    print("表情")
                    self!.switchEmoticonButton()
                case .Add:
                    print("加号")
                }
            }
        
        return toolBar
    }()
    
    private lazy var pictureView:APPLEComposePictureView = {
         let  pictureView = APPLEComposePictureView()
        pictureView.addImagesClourse = {[weak self] in
            
            self?.selectPictureButton()
        }
        return pictureView
    }()
    
    private lazy var emoticonKeyboard:APPLEEmoticonKeyboard = {
        let emoticonKeyboard = APPLEEmoticonKeyboard()
        emoticonKeyboard.frame.size = CGSize(width: mainScreenW, height: 216)
        return emoticonKeyboard
    }()
    @objc private func selectPictureButton(){
        let vc = UIImagePickerController()
        vc.delegate=self
        vc.sourceType = .PhotoLibrary
        presentViewController(vc, animated: true, completion: nil)
    }
    
    @objc private func switchEmoticonButton(){
        
        toolBarAnimation = false
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        toolBarAnimation = true
        
        toolBar.isSystemKeyboard = textView.inputView == nil
        textView.becomeFirstResponder()
    }
    
    @objc private func sendMessage(){
        print("123")
        if pictureView.images.count == 0{
            // 发送文字微博
            update()
        }else{
            upload()
        }
    }
    /// 发送图片微博
    private func upload(){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let params = [
            "access_token": APPLEUserAccountViewModel.sharedViewModel.accessToken!,
            "status": textView.emoticonText
        ]
        
        let manager = AFHTTPSessionManager()
        manager.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
            // 拼装上传图片
            let image = self.pictureView.images.first!
            
            /**
            data:要上传二进制数据
            name:接口里面定义的参数
            fileName:上传到后台的文件名，一般可乱写，后台会处理
            mimeType: 告诉后台我要上传的文件是什么类型：
            image/png: 大类型/小类型
            application/octet-stream
            */
            formdata.appendPartWithFileData(UIImagePNGRepresentation(image)!, name: "pic", fileName: "aab", mimeType: "image/png")
            }, progress: nil, success: { (_, response) -> Void in
                print("1")
                // 请求成功回调
                SVProgressHUD.showSuccessWithStatus("发送成功")
            }) {(_, error) -> Void in
                print("2")
                // 请求失败回调
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
        
    }
    
    /// 发送文字微博
    private func update(){
        APPLENetworkTools.sharedTools.update(APPLEUserAccountViewModel.sharedViewModel.accessToken!, status: textView.emoticonText) { (response, error) -> () in
            if error != nil {
                // 发送失败
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
    }
    
    @objc private func back(){
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}

extension APPLEComposeViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
       
        pictureView.addImage(image)
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension APPLEComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled=textView.hasText()
    }
}

extension APPLEComposeViewController{
    
    private func setUpUI(){
        
        view.backgroundColor=UIColor.whiteColor()
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "返回", targat: self, action: "back")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        
        if let name=APPLEUserAccountViewModel.sharedViewModel.userAccount?.screen_name{
            let titleString = "发微博\n\(name)"
            let attr = NSMutableAttributedString(string: titleString)
            let range = (titleString as NSString).rangeOfString(name)
            attr.addAttribute(NSFontAttributeName, value:UIFont.systemFontOfSize(14), range: range)
            attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
            titleView.attributedText = attr
            titleView.sizeToFit()
            navigationItem.titleView=titleView
        }else{
            navigationItem.title="发微博"
        }
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardFrameWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonDidSelected:", name: "HMEmoticonDidSelectedNotification", object: nil)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_updateConstraints { (make) -> Void in
            make.leading.equalTo(textView).offset(APPLEComposeViewControllerMargin)
            make.width.equalTo(textView).offset(-2*APPLEComposeViewControllerMargin)
            make.top.equalTo(textView).offset(100)
            make.height.equalTo(pictureView.snp_width)
        }
    }
    
//    NSConcreteNotification 0x7fc766548e60 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
//    UIKeyboardAnimationCurveUserInfoKey = 7;
//    UIKeyboardAnimationDurationUserInfoKey = "0.25";
//    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
//    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
//    UIKeyboardIsLocalUserInfoKey = 1;
//    }}
    @objc private func keyBoardFrameWillChange(noti:NSNotification){
        print(noti)
        
        if toolBarAnimation == false{
            return
        }
        
        if let changeFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(){
            toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(changeFrame.origin.y - mainScreenH)
            })
        }
        
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.toolBar.layoutIfNeeded()
        }
    }
    
    @objc private func emoticonDidSelected(info:NSNotification){
       let emoticon = info.userInfo!["emoticon"] as! APPLEEmoticon
       textView.insertEmoyicon(emoticon)
                
    }
}